#include "GLApplication.h"
#include "GLWindow.h"
using namespace ScienceGL;

GLApplication::GLApplication()
{
	
}

bool GLApplication::Init()
{
	glEnable(GL_DEPTH_TEST);
	glClearColor(0.0f, 0.0f, 0.0f, 0.0f);

	return true;
}

void GLApplication::Prepare(float dt)
{
	
}

void GLApplication::Render()
{
	glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
	glLoadIdentity();	
}

void GLApplication::Shutdown()
{

}

void GLApplication::OnResize(int width, int height)
{
	glViewport(0, 0, width, height);
	glMatrixMode(GL_PROJECTION);
	glLoadIdentity();
	gluPerspective(45.0f, float(width) / float(height), 1.0f, 1000.0f);
	glMatrixMode(GL_MODELVIEW);
	glLoadIdentity();
}

GLApplication::~GLApplication()
{
}


void GLApplication::runApplication(HINSTANCE hInstance, GLApplication* gameApplicaion)
{
	GLWindow window;
	window.SetGLApplication(gameApplicaion);

	if (window.Create(hInstance, 800, 600, 32, false) != GLError::GLError_Success)
		return;

	gameApplicaion->Init();

	LARGE_INTEGER time1, time2, freq;
	QueryPerformanceFrequency(&freq);
	QueryPerformanceCounter(&time1);
	double elapsedTime = 0;
	while (window.IsRunning())
	{
		QueryPerformanceCounter(&time1);

		window.ProcessEvents();
		gameApplicaion->Prepare(elapsedTime);
		gameApplicaion->Render();
		window.SwapBuffers();

		QueryPerformanceCounter(&time2);
		elapsedTime = double(time2.QuadPart - time1.QuadPart) / double(freq.QuadPart);
	}

	gameApplicaion->Shutdown();
	window.Destroy();
}